#include <slothttpd/http/response.hpp>
#include <slothttpd/http/http.hpp>

#include <cstdio>

#include <boost/asio.hpp>

namespace slothttpd {
namespace http {

response::response() :
    buffer_count_(3) // 1) http_11, 2) status_line_, 3) crlf
{
    status_line(http::status::ok.status_line);
}

void response::push_back(boost::asio::const_buffer buffer)
{
    if (buffer_count_ >= buffers_.size()) {
        
    } else {
        buffers_[buffer_count_] = buffer;
        buffer_count_++;
    }
}

const_buffer_range_t response::get_buffers_range()
{
    buffers_[0] = boost::asio::buffer(http::http11);
    buffers_[1] = boost::asio::buffer(status_line_.begin(), status_line_.size());
    buffers_[2] = boost::asio::buffer(crlf);
    
    return const_buffer_range_t(buffers_.data(), buffers_.data() + buffer_count_);
}

void response::status_line(char_range_t line)
{
    status_line_ = line;
}

void response::status_line(const std::string &line)
{
    status_line_ = char_range_t(const_cast<char*>(line.data()),
                                const_cast<char*>(line.data() + line.size()));
}

std::ostream &operator<<(std::ostream &os, const response &r)
{
    os << " --- dumping response ---\n";
    for (std::size_t i = 0; i < r.buffer_count_; i++) {
        auto &b = r.buffers_[i];
        os.write(boost::asio::buffer_cast<const char*>(b), boost::asio::buffer_size(b));
    }
    
    return os;
}

}
}
